package com.example.msgsendmail;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.Date;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;

public class MainActivity extends AppCompatActivity {

    private static MainActivity instance;
    private static final int PERMISSION_REQUEST_CODE = 123;
    private SwitchCompat serviceSwitch;
    private TextView statusTextView;
    private TextView smsPermissionTextView;
    private TextView internetPermissionTextView;
    private TextView fromEmailTextView;
    private TextView toEmailTextView;
    private TextView smtpServerTextView;
    private TextView logTextView;

    public static MainActivity getInstance() {
        return instance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化视图
        initViews();
        
        // 设置开关监听事件
        serviceSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                startService();
            } else {
                stopService();
            }
        });


        // 更新UI状态
        updateUI();
        
        // 检查权限状态
        checkPermissions();
    }

    private void initViews() {
        serviceSwitch = findViewById(R.id.serviceSwitch);
        statusTextView = findViewById(R.id.statusTextView);
        smsPermissionTextView = findViewById(R.id.smsPermissionTextView);
        internetPermissionTextView = findViewById(R.id.internetPermissionTextView);
        logTextView = findViewById(R.id.logTextView);
    }

    // 在checkPermissions方法中添加READ_SMS权限检查
    private void checkPermissions() {
        boolean hasSmsPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED;
        boolean hasReadSmsPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED;
        boolean hasInternetPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED;
        
        // 更新短信接收权限状态（同时显示读取权限状态）
        smsPermissionTextView.setText("短信权限：" + 
            (hasSmsPermission ? "接收已获取" : "接收未获取") + ", " + 
            (hasReadSmsPermission ? "读取已获取" : "读取未获取"));
        smsPermissionTextView.setTextColor(getResources().getColor(
            (hasSmsPermission && hasReadSmsPermission) ? R.color.permission_granted : R.color.permission_denied));
        
        // 移除对不存在控件的引用
        // TextView readSmsPermissionTextView = findViewById(R.id.readSmsPermissionTextView);
        // if (readSmsPermissionTextView != null) {
        //     readSmsPermissionTextView.setText("短信读取权限：" + (hasReadSmsPermission ? "已获取" : "未获取"));
        //     readSmsPermissionTextView.setTextColor(getResources().getColor(hasReadSmsPermission ? R.color.permission_granted : R.color.permission_denied));
        // }
        
        internetPermissionTextView.setText("网络权限：" + (hasInternetPermission ? "已获取" : "未获取"));
        internetPermissionTextView.setTextColor(getResources().getColor(hasInternetPermission ? R.color.permission_granted : R.color.permission_denied));
    }
    
    // 在startService方法中添加
    // 在类的顶部添加
    private SmsContentObserver smsContentObserver;
    
    // 在 startService 方法中添加
    private void startService() {
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, 
                new String[]{Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS}, 
                PERMISSION_REQUEST_CODE);
            return;
        }
        
        // 针对小米手机的特殊处理
        if (isMiuiDevice()) {
            addLogEntry("检测到小米设备，正在进行特殊权限处理...");
            // 尝试读取短信，触发系统权限请求
            boolean hasRealPermission = tryReadSms();
            if (!hasRealPermission) {
                // 引导用户手动设置权限
                showMiuiPermissionDialog();
                serviceSwitch.setChecked(false);
                return;
            }
            addLogEntry("小米设备权限处理完成");
        }
    
        // 注册ContentObserver监听短信变化
        if (smsContentObserver == null) {
            smsContentObserver = new SmsContentObserver(this, new android.os.Handler());
            getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, smsContentObserver);
            addLogEntry("已注册短信内容观察器");
        }
    
        // 启动服务
        SMSReceiver.setServiceRunning(true);
        updateUI();
        addLogEntry("短信转发服务已启动");
        Toast.makeText(this, "短信转发服务已启动", Toast.LENGTH_SHORT).show();
    }
    
    // 在 stopService 方法中添加
    private void stopService() {
        // 取消注册ContentObserver
        if (smsContentObserver != null) {
            getContentResolver().unregisterContentObserver(smsContentObserver);
            smsContentObserver = null;
            addLogEntry("已取消注册短信内容观察器");
        }
        
        SMSReceiver.setServiceRunning(false);
        updateUI();
        addLogEntry("短信转发服务已停止");
        Toast.makeText(this, "短信转发服务已停止", Toast.LENGTH_SHORT).show();
    }
    
    // 在 onDestroy 方法中添加
    @Override
    protected void onDestroy() {
        // 取消注册ContentObserver
        if (smsContentObserver != null) {
            getContentResolver().unregisterContentObserver(smsContentObserver);
            smsContentObserver = null;
        }
        
        super.onDestroy();
        if (instance == this) {
            instance = null;
        }
    }
    
    // 显示MIUI权限设置对话框
    private void showMiuiPermissionDialog() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("需要额外授权")
            .setMessage("检测到您使用的是小米/红米手机，需要手动开启所有短信权限。\n\n" +
                     "请在权限设置页面中：\n" +
                     "1. 将'读取短信'和'接收短信'权限设置为'始终允许'\n" +
                     "2. 特别注意开启'通知类短信'权限\n" +
                     "3. 在'安全中心'中关闭短信保护功能\n" +
                     "4. 在'设置-应用管理-权限管理-自启动'中允许本应用自启动\n" +
                     "5. 在'设置-应用管理-权限管理-省电策略'中设置为'无限制'")
            .setPositiveButton("去设置", (dialog, which) -> {
                try {
                    // 尝试跳转到MIUI的权限设置页面
                    Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                    intent.putExtra("extra_pkgname", getPackageName());
                    intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                    startActivity(intent);
                } catch (Exception e) {
                    // 如果失败，尝试其他方式
                    try {
                        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                        intent.putExtra("extra_pkgname", getPackageName());
                        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
                        startActivity(intent);
                    } catch (Exception e1) {
                        // 如果还是失败，跳转到应用详情页面
                        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.fromParts("package", getPackageName(), null));
                        startActivity(intent);
                    }
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    // 判断是否为小米设备
    private boolean isMiuiDevice() {
        return Build.MANUFACTURER.toLowerCase().contains("xiaomi");
    }
    
    // 尝试读取短信，触发系统权限请求，同时尝试读取通知类短信
    private boolean tryReadSms() {
        boolean hasRealPermission = false;
        try {
            // 尝试读取收件箱短信
            Uri inboxUri = Uri.parse("content://sms/inbox");
            ContentResolver cr = getContentResolver();
            String[] projection = new String[]{"_id"};
            Cursor inboxCur = cr.query(inboxUri, projection, null, null, "date desc");
            if (inboxCur != null) {
                inboxCur.close();
                hasRealPermission = true;
                addLogEntry("成功读取收件箱短信");
            }
            
            // 尝试读取通知类短信
            Uri notificationUri = Uri.parse("content://sms/notification");
            Cursor notificationCur = cr.query(notificationUri, projection, null, null, "date desc");
            if (notificationCur != null) {
                notificationCur.close();
                addLogEntry("成功读取通知类短信");
            } else {
                addLogEntry("无法读取通知类短信，请手动开启权限");
            }
            
            // 尝试读取所有短信
            Uri allSmsUri = Uri.parse("content://sms");
            Cursor allSmsCur = cr.query(allSmsUri, projection, null, null, "date desc");
            if (allSmsCur != null) {
                allSmsCur.close();
                addLogEntry("成功读取所有短信");
            }
        } catch (Exception e) {
            e.printStackTrace();
            addLogEntry("读取短信失败: " + e.getMessage());
        }
        return hasRealPermission;
    }

    private void sendTestEmail() {
        addLogEntry("正在发送测试邮件...");
        EmailSender.sendEmail("短信转发服务测试邮件", "这是一封测试邮件，用于验证短信转发服务的邮件发送功能是否正常。", success -> {
            String message = success ? "测试邮件发送成功" : "测试邮件发送失败，请检查邮箱配置";
            addLogEntry(message);
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
        });
    }

    private void updateUI() {
        boolean isRunning = SMSReceiver.isServiceRunning();
        serviceSwitch.setChecked(isRunning);
        statusTextView.setText("服务状态：" + (isRunning ? "已启动" : "已停止"));
        statusTextView.setTextColor(getResources().getColor(isRunning ? R.color.status_running : R.color.status_stopped));
    }


    
    public void addLogEntry(String message) {
        String timestamp = (String) DateFormat.format("yyyy-MM-dd HH:mm:ss", new Date());
        String logEntry = timestamp + " - " + message + "\n";
        
        // 在UI线程更新日志
        runOnUiThread(() -> {
            String currentLog = logTextView.getText().toString();
            if (currentLog.equals("暂无转发记录")) {
                logTextView.setText(logEntry);
            } else {
                logTextView.setText(logEntry + currentLog);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startService();
                checkPermissions(); // 更新权限状态显示
            } else {
                serviceSwitch.setChecked(false); // 权限被拒绝，关闭开关
                Toast.makeText(this, "需要短信权限才能转发短信", Toast.LENGTH_LONG).show();
                addLogEntry("短信权限被拒绝，无法启动服务");
            }
        }
    }

}